const express = require('express')
const route = express.Router()
const controller = require('./controller')
const multiparty = require('multiparty')
var fs = require('fs')
var path = require('path')

route.get('/', controller.list)

route.get('/:id', controller.detail)

route.put('/', controller.add)

route.post('/:id', controller.change)

route.delete('/:id', controller.remove)

route.get('/genarate/assets', controller.genarateAssets)

route.get('/genarate/:id', controller.genaratePage)

route.post('/upload/file', function (req, res) {
  var form = new multiparty.Form({uploadDir: process.cwd()})
  form.parse(req, function (err, fields, files) {
    if (err) {
      res.send('err')
      return
    }
    var retFilePaths = []
    for (var key in files.file) {
      var file = files.file[key]
      console.log(file)
      var newPath = path.join(process.cwd(), global.env === 'dev' ? 'static' : 'dist/static', '.img', file.originalFilename)
      console.log(newPath, newPath.replace(process.cwd(), ''))
      fs.rename(file.path, newPath, function (err) {
        if (err) {
          console.log(err)
        }
        retFilePaths.push({key: file.fieldName, path: newPath.replace(process.cwd(), '')})
        res.send(retFilePaths)
      })
    }
  })
})

module.exports = route
